import { login, logout, getInfo, loginBySms } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { isEmpty } from '@/utils/validate';
import defAva from '@/assets/images/profile.jpg';
import { connectWebSocket } from '@/utils/websocket';
import { ElNotification } from 'element-plus';
import { h } from 'vue';


const useUserStore = defineStore('user', {
	state: () => ({
		token: getToken(),
		id: '',
		name: '',
		nickName: '',
		avatar: '',
		roles: [],
		permissions: [],
		websocketMsg: '',
		unreadMessages: []
	}),
	actions: {
		// 登录
		login(userInfo) {
			const username = userInfo.username.trim();
			const password = userInfo.password;
			const code = userInfo.code;
			const uuid = userInfo.uuid;
			return new Promise((resolve, reject) => {
				login(username, password, code, uuid)
					.then(res => {
						let data = res.data;
						setToken(data.access_token);
						this.token = data.access_token;
						resolve();
					})
					.catch(error => {
						reject(error);
					});
			});
		},
		smsLogin(phone, code) {
			return new Promise((resolve, reject) => {
				loginBySms(phone, code)
					.then(res => {
						let data = res.data;
						setToken(data.access_token);
						this.token = data.access_token;
						resolve();
					})
					.catch(error => {
						reject(error);
					});
			});
		},
		// 获取用户信息
		getInfo() {
			return new Promise((resolve, reject) => {
				getInfo()
					.then(res => {
						const user = res.user;
						const avatar = isEmpty(user.avatar) ? defAva : user.avatar;
						if (res.roles && res.roles.length > 0) {
							// 验证返回的roles是否是一个非空数组
							this.roles = res.roles;
							this.permissions = res.permissions;
						} else {
							this.roles = ['ROLE_DEFAULT'];
						}
						this.id = user.userId;
						this.name = user.userName;
						this.nickName = user.nickName;
						this.avatar = avatar;
						
						// 👇 在用户信息设置完成后连接 WebSocket
						connectWebSocket(this.id, (msg) => {
							this.websocketMsg = msg;
							this.handleWebSocketMessage(msg);
						});
						
						resolve(res);
					})
					.catch(error => {
						reject(error);
					});
			});
		},
		// 退出系统
		logOut() {
			return new Promise((resolve, reject) => {
				logout(this.token)
					.then(() => {
						this.token = '';
						this.roles = [];
						this.permissions = [];
						removeToken();
						resolve();
					})
					.catch(error => {
						reject(error);
					});
			});
		},
		// 处理WebSocket消息
		handleWebSocketMessage(msg) {
			try {
				const messageData = JSON.parse(msg);
				// 新的消息结构：{"content":{"type":"admin","content":"...","timestamp":...},"read":false}
				if (messageData.content && messageData.content.type === 'admin') {
					const content = messageData.content;
					const isRead = messageData.read || false;
					
					// 添加到消息列表
					this.unreadMessages.push({
						id: Date.now() + Math.random(), // 生成唯一ID
						type: content.type,
						content: content.content,
						timestamp: content.timestamp,
						isRead: isRead,
						receivedAt: new Date()
					});
					
					// 只有当消息未读时才显示通知
					if (!isRead) {
						const notification = ElNotification({
							title: '新消息通知',
							message: h('div', { 
								style: 'cursor: pointer;'
							}, content.content),
							type: 'info',
							duration: 5000,
							onClick: () => {
								// 点击通知跳转到消息页面
								import('vue-router').then(({ useRouter }) => {
									const router = useRouter();
									router.push('/messages');
								}).catch(() => {
									// 如果useRouter不可用，使用window.location
									window.location.href = '/messages';
								});
								notification.close();
							}
						});
					}
				}
			} catch (error) {
				console.error('解析WebSocket消息失败:', error);
			}
		},
		// 标记消息为已读
		markMessageAsRead(messageId, timestamp) {
			const message = this.unreadMessages.find(msg => msg.id === messageId);
			if (message) {
				message.isRead = true;
				// 发送已读确认到服务器
				import('@/utils/websocket').then(({ sendWebSocketMessage }) => {
					sendWebSocketMessage(JSON.stringify({
						type: "read",
						timestamp: timestamp
					}));
				});
			}
		},
		// 获取未读消息数量
		getUnreadCount() {
			return this.unreadMessages.filter(msg => !msg.isRead).length;
		},
		// 删除消息
		deleteMessage(messageId, timestamp) {
			const index = this.unreadMessages.findIndex(msg => msg.id === messageId);
			if (index !== -1) {
				this.unreadMessages.splice(index, 1);
				// 发送删除确认到服务器
				import('@/utils/websocket').then(({ sendWebSocketMessage }) => {
					sendWebSocketMessage(JSON.stringify({
						type: "delete",
						timestamp: timestamp
					}));
				});
			}
		}
	},
});

export default useUserStore;
